package com.m3839.sdk.pay.ui;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.m3839.sdk.common.base.SimpleViewHolder;
import com.m3839.sdk.common.util.ResourcesUtils;
import com.m3839.sdk.pay.bean.PayChannel;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:HykbPayChannelsAdapter
 *
 * @author 陈宝阳
 * @create 2020/8/7 10:18
 */
public class PayChannelsAdapter extends BaseAdapter {

  private final Context context;
  private final List<PayChannel> payChannels = new ArrayList<>();

  /**
   * 选中的选项
   */
  private PayChannel selectPayChannel;

  public PayChannelsAdapter(Context context, List<PayChannel> channels) {
    this.context = context;
    this.payChannels.addAll(channels);
    if(this.payChannels.size() > 0) {
      selectPayChannel = payChannels.get(0);
    }
  }

  @Override
  public int getCount() {
    return payChannels.size();
  }

  @Override
  public PayChannel getItem(int position) {
    return payChannels.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  @Override
  public View getView(final int position, View convertView, ViewGroup parent) {
    SimpleViewHolder viewHolder;
    //判断是否有缓存
    if (convertView == null) {
      convertView = LayoutInflater.from(context)
          .inflate(ResourcesUtils.getLayoutId(context, "hykb_pay_item_channel"), null);
      viewHolder = new SimpleViewHolder(convertView);
      convertView.setTag(viewHolder);
    } else {
      //得到缓存的布局
      viewHolder = (SimpleViewHolder) convertView.getTag();
    }

    //设置图标
    viewHolder.setImageResource("iv_pay_channel_icon", payChannels.get(position).payChannelIcon);
    //设置名称
    viewHolder.setTextView("tv_pay_channel_name", payChannels.get(position).payChannelName);
    //设置选择项
    CheckBox payChannelChoiceCb = viewHolder.findView("cb_pay_channel_choice");
    payChannelChoiceCb.setChecked(payChannels.get(position).select);
    payChannelChoiceCb.setClickable(false);
    //设置选择事件
    convertView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        choicePayChannel(position);
        selectPayChannel = payChannels.get(position);
      }
    });
    return convertView;
  }

  public PayChannel getSelectPayChannel() {
    return selectPayChannel;
  }

  public void choicePayChannel(int position) {
    for (int i = 0; i < payChannels.size(); i++) {
      payChannels.get(i).select = position == i;
    }

    notifyDataSetChanged();
  }

}
